package org.arduomo.irserial;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

public class IRConfig {

	private static final String BEGIN_CODES = "begin codes";
	private static final String END_REMOTE = "end remote";
	private static final String END_CODES = "end codes";
	private static final String BEGIN_REMOTE = "begin remote";
	public static final String PRE_DATA = "pre_data";
	
	private static final int NONE = 0;
	private static final int REMOTE = 1;
	private static final int CODES = 2;

	private HashMap<String, String> propertyMap;
	private HashMap<String, String> codesMap;

	public IRConfig() {
		super();
		propertyMap = new HashMap<String, String>();
		codesMap = new HashMap<String, String>();
	}

	public void addProperty(String key, String value) {
		if (!propertyMap.containsKey(key)) {
			propertyMap.put(key, value);
		}
	}

	public void addCode(String key, String value) {
		if (!codesMap.containsKey(key)) {
			codesMap.put(key, value);
		}
	}

	public String getProperty(String key) {
		return propertyMap.get(key);
	}

	public String getCode(String key) {
		return codesMap.get(key);
	}

	public Set<String> getPropertyNames() {
		return propertyMap.keySet();
	}

	public Set<String> getCodeNames() {
		return codesMap.keySet();
	}

	public static IRConfig parseFile(File file) throws IOException {
		int section = NONE;
		IRConfig result = new IRConfig();
		FileReader reader = new FileReader(file);
		BufferedReader bufferedReader = new BufferedReader(reader);
		String line = "";
		bufferedReader.readLine();
		while ((line = bufferedReader.readLine()) != null) {
			line = line.trim();
			if (line.equals(BEGIN_REMOTE)) {
				section = REMOTE;
			} else if (line.equals(BEGIN_CODES)) {
				section = CODES;
			} else if (line.equals(END_REMOTE)) {
				section = NONE;
			} else if (line.equals(END_CODES)) {
				section = REMOTE;
			} else if (!line.equals("") && !line.startsWith("#")) {
				int indexOf = line.indexOf(" ");
				String key = line.substring(0, indexOf).trim();
				String value = line.substring(indexOf).trim();
				switch (section) {
				case REMOTE:
					result.addProperty(key, value);
					break;
				case CODES:
					result.addCode(key, value);
					break;
				default:
					break;
				}
			}
		}
		return result;
	}
}
